package vcs.media;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import vcs.bluetoothmusic.BluetoothMusic;
import vcs.media.player.AnimationView;
import vcs.media.player.PlayList;
import vcs.media.player.SongManager;
import vcs.media.player.Utilities;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


public class MainRun extends Activity implements OnSeekBarChangeListener, OnCompletionListener{
	
	//Media media;
	SeekBar songProgressBar;
	Handler handler = new Handler();
	Utilities utils;
	MediaPlayer media;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000;
	private boolean isRepeat = false;
	private boolean isShuffle = false;
	
	
	//Animation
	AnimationView anim_view;
	AnimationView anim_view1;
	
	//Bluetooth service
	//BluetoothService blueService = new BluetoothService();
	
	//Button
	ImageButton bt_play;
	ImageButton bt_list;
	ImageButton bt_next;
	ImageButton bt_pre;
	ImageButton bt_preSpeed;
	ImageButton bt_nextSpeed;
	ImageButton bt_repeat;
	ImageButton bt_shuffle;
	
	
	//Textbox
	TextView tv_songtitle;
	TextView tv_realTime;
	TextView tv_sizeFile;
	
	//Array song list
	SongManager songManager;
	ArrayList<HashMap<String, String>> songList = new ArrayList<HashMap<String,String>>();
	int currentSong = 0;
	
	//Path of Song
	String pathSong = "";
	
	//Temp name of song
	String tempNameSong = "";
	
	//MediaMetadataRetriever
	MediaMetadataRetriever meta;
	String intentArt = "";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scene_main_media);
		
//		blueService.NotSupportBluetooth(this);
//		if(!blueService.isEnable()){
//			startActivityForResult(blueService.autoOpen(), blueService.REQUEST_ENABLE_BT);
//		}
		
		
		
		media = new MediaPlayer();
		utils = new Utilities();
		songManager = new SongManager();
		songList = songManager.getPlayList();
		
		
		
		songProgressBar = (SeekBar)findViewById(R.id.songProgressBar);
		songProgressBar.setOnSeekBarChangeListener(MainRun.this);
		media.setOnCompletionListener(MainRun.this);
		
		
//		try {
//			Item.filePath = getAssets().openFd("song/sample.mp3");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
//		media.setFilePath();
//		//media.Play();
//		songProgressBar.setProgress(0);
//		songProgressBar.setMax(100);
//		updateProgressBar();
		bt_play = (ImageButton)findViewById(R.id.bt_play);
		bt_next = (ImageButton)findViewById(R.id.bt_next);
		bt_pre = (ImageButton)findViewById(R.id.bt_pre);
		bt_nextSpeed = (ImageButton)findViewById(R.id.bt_nextSpeed);
		bt_preSpeed = (ImageButton)findViewById(R.id.bt_preSpeed);
		bt_repeat = (ImageButton)findViewById(R.id.bt_repeat);
		bt_shuffle = (ImageButton)findViewById(R.id.bt_shuffle);
		bt_list = (ImageButton)findViewById(R.id.bt_list);
		tv_songtitle = (TextView)findViewById(R.id.songTitle);
		tv_realTime = (TextView)findViewById(R.id.realTime);
		tv_sizeFile = (TextView)findViewById(R.id.sizeFile);

		
		//
		
		anim_view = (AnimationView) this.findViewById(R.id.anim_view);
        anim_view.loadAnimation("spark", 18,0,0);
        anim_view1 = (AnimationView) this.findViewById(R.id.anim_view1);
        
        // You can call this method inside thread
        anim_view1.loadAnimation("spark", 18,0,0);
		//songIndex(currentSong);
		
		bt_play.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(songList.isEmpty()){
					Toast.makeText(MainRun.this, "No have a song in list song", Toast.LENGTH_SHORT).show();
					return;
				}
				//media.setFilePath();
				if(media.isPlaying()){
					if(media != null){
						media.pause();
						bt_play.setImageResource(R.drawable.bt_play);
					}
				}else{
					if(media != null){
						media.start();
						updateProgressBar();
						bt_play.setImageResource(R.drawable.bt_pause);
					}
				}
			}
		});
		
		bt_list.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), PlayList.class);
				startActivityForResult(intent, 100);
			}
		});
	
		bt_next.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(currentSong < (songList.size() - 1)){
					currentSong++;
					songIndex(currentSong);
				}else{
					currentSong = 0;
					songIndex(currentSong);
				}
				
			}
		});
		
		bt_pre.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(currentSong > 0){
					currentSong--;
					songIndex(currentSong);
				}else{
					currentSong = songList.size() - 1;
					songIndex(currentSong);
				}
			}
		});
		
		bt_nextSpeed.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				int currentPosition = media.getCurrentPosition();
				if(currentPosition + seekForwardTime <= media.getDuration()){
					media.seekTo(currentPosition + seekForwardTime);
				}else{
					media.seekTo(media.getDuration());
				}
				
			}
		});
		
		bt_preSpeed.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				int currentPosition = media.getCurrentPosition();
				if(currentPosition - seekBackwardTime >= 0){
					media.seekTo(currentPosition - seekBackwardTime);
				}else{
					media.seekTo(0);
				}
			}
		});
		
		bt_repeat.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = false;
					bt_repeat.setImageResource(R.drawable.btn_repeat);
				}else{
					isRepeat = true;
					isShuffle = false;
					bt_repeat.setImageResource(R.drawable.btn_repeat_focused);
					bt_shuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});
		
		bt_shuffle.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = false;
					bt_shuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					isShuffle = true;
					isRepeat = false;
					bt_shuffle.setImageResource(R.drawable.btn_shuffle_focused);
					bt_repeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});
	}
	
	
	/*
	 * Play song index
	 * param: index
	 */
	private void songIndex(int index){
		
		
		
		try {
			
			meta = new MediaMetadataRetriever();
			meta.setDataSource(songList.get(index).get("songPath"));
			String a = meta.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
			Toast.makeText(MainRun.this, a, Toast.LENGTH_LONG).show();
			
			media.reset();
			media.setDataSource(songList.get(index).get("songPath"));
			
			pathSong = songList.get(index).get("songPath");
			media.prepare();
			media.start();
			
			bt_play.setImageResource(R.drawable.bt_pause);
			tv_songtitle.setText(songList.get(index).get("songTitle"));
			
			//Get name of the Song
			tempNameSong = songList.get(index).get("songTitle");
			
			//Progress Bar
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);
			updateProgressBar();
			
			//Animation for Background
			anim_view.playAnimation();
	        anim_view1.playAnimation();
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		media.release();
		anim_view=null;
        anim_view1=null;
      //Button
        songProgressBar = null;
    	bt_play = null;
    	bt_list = null;
    	bt_next = null;
    	bt_pre = null;
    	bt_preSpeed = null;
    	bt_nextSpeed = null;
    	bt_repeat = null;
    	bt_shuffle = null;
    	
    	
    	//Textbox
    	tv_songtitle = null;
    	tv_realTime = null;
    	tv_sizeFile = null;
    	handler.removeCallbacks(mUpdateTimeTask);
    	finish();
	}

	/*
	 * Get index song from listSong
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == 100){
			currentSong = data.getExtras().getInt("songIndex");
			songIndex(currentSong);
		}
		
		if(resultCode == 200){
			Bundle bundleArt = data.getExtras();
			songManager = new SongManager();
			songList = (ArrayList<HashMap<String, String>>)bundleArt.getSerializable("mediatype");
			currentSong = bundleArt.getInt("songIndexArt");
			songIndex(currentSong);
		}
		
		if(resultCode == 300){
			Bundle bundleArt = data.getExtras();
			songManager = new SongManager();
			songList = (ArrayList<HashMap<String, String>>)bundleArt.getSerializable("mediatype");
			currentSong = bundleArt.getInt("songIndexArt");
			songIndex(currentSong);
		}
		if(resultCode == 400){
			Bundle bundleArt = data.getExtras();
			songManager = new SongManager();
			songList = (ArrayList<HashMap<String, String>>)bundleArt.getSerializable("mediatype");
			currentSong = bundleArt.getInt("songIndexArt");
			songIndex(currentSong);
		}
		
	}
	
	//Update seekbar
	public void updateProgressBar(){
		handler.postDelayed(mUpdateTimeTask, 100);
	}
	
	Runnable mUpdateTimeTask = new Runnable() {
		
		@Override
		public void run() {
			long totalDuration = media.getDuration();
			long currentDuration = media.getCurrentPosition();
			
			tv_realTime.setText("" + utils.milliSecondsToTimer(currentDuration));
			tv_sizeFile.setText("" + utils.milliSecondsToTimer(totalDuration));
			
			int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			songProgressBar.setProgress(progress);
			handler.postDelayed(this, 100);
		}
	};
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = (int)media.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
 
        // forward or backward to certain seconds
        media.seekTo(currentPosition);
 
        // update timer progress again
        updateProgressBar();
	}

	
	
	@Override
	public void onCompletion(MediaPlayer arg0) {
		
		if (isRepeat) {
			songIndex(currentSong);
		} else if (isShuffle) {
			Random rand = new Random();
			currentSong = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
			songIndex(currentSong);
		}else{
			if(currentSong < (songList.size() - 1)){
				currentSong++;
				songIndex(currentSong);
			}else{
				currentSong = 0;
				songIndex(0);
			}
		}
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.option_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		
		Intent send = new Intent(this, BluetoothMusic.class);
		switch (item.getItemId()) {
		case R.id.shareMusic:
			if(pathSong.trim().equals("") || pathSong == null){
				return false;
			}
			
			if(media.isPlaying()){
				media.pause();
				bt_play.setImageResource(R.drawable.bt_play);
			}
			
			send.putExtra("PathSong", pathSong);
			send.putExtra("Share", true);
			send.putExtra("NameSong", tempNameSong);
			startActivity(send);
			return true;
		case R.id.receiveMusic:
			
			if(media.isPlaying()){
				media.pause();
				bt_play.setImageResource(R.drawable.bt_play);
			}
			
			send.putExtra("Share", false);
			startActivity(send);
			
			return true;
		case R.id.artist:
			send = new Intent(getApplicationContext(), Artist.class);
			send.putExtra("mediatype", "artist");
			startActivityForResult(send, 200);
			return true;
		case R.id.author:
			send = new Intent(getApplicationContext(), Artist.class);
			send.putExtra("mediatype", "author");
			startActivityForResult(send, 300);
			return true;
		case R.id.genre:
			send = new Intent(getApplicationContext(), Artist.class);
			send.putExtra("mediatype", "genre");
			startActivityForResult(send, 400);
			return true;
		}
		return false;
	}
}
